<script lang="ts" setup>
import { ActionBar, ActionBarButton, ActionBarIcon, Loading, Popup, showConfirmDialog, showFailToast, showSuccessToast } from 'vant'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import html2canvas from 'html2canvas'
import lodash from 'lodash'
import { Common } from '~/common'
import { OrderApi } from '~/api/OrderApi'
import { OrderModel } from '~/model/OrderModel'
import PairsView from '~/components/common/PairsView.vue'
import DeliveryView from '~/components/order/DeliveryView.vue'
import { protectedAction } from '~/utils'
import { MaterialModel, OrderItemModel } from '~/model'

defineOptions({
  name: 'OrdersDetail',
})

const route = useRoute()
const router = useRouter()

const id = Number.parseInt(route.query.id as string)
const order = ref(null as OrderModel | null)

const imgDst = ref(null as any)
const imgDstShown = ref(false)

const printing = ref(false)

onMounted(async () => {
  order.value = await OrderApi.get(id)

  // 添加运费和总计
  if (
    order.value
    && order.value.needDelivery
    && order.value.fare > 0
    && !order.value.items.find(x => x.material?.name === '运费')
  ) {
    const material = new MaterialModel()
    material.name = '运费'
    const orderItem = new OrderItemModel()
    orderItem.material = material
    orderItem.quantity = 1
    orderItem.unitPrice = order.value?.fare
    orderItem.amount = order.value?.fare
    order.value?.items.push(orderItem)
  }

  // const orderOfCustomerAndTheDay = allOrders.filter((x: any) => {
  //   if (order.value === null) {
  //     return false
  //   }
  //   const isTheSamePerson = x.consumerId === (order.value as any).consumerId
  //   const _day = (d: number) => Number.parseInt((d / 86400000).toString())
  //   const isTheSameDay = _day(x.date) === _day(order.value.date.valueOf())
  //   return isTheSamePerson && isTheSameDay
  // })

  // orderOfCustomerAndTheDay.sort((a, b) => a.id - b.id)
})

async function onPrint() {
  if (!order.value) {
    return
  }

  // 检查是否已经打印过了
  if (order.value.stub) {
    try {
      await showConfirmDialog({
        message: '存根已经录好了，确认要再次打印吗？',
        closeOnClickOverlay: true,
      })
    }
    catch (err) {
      return
    }
  }

  // 检查空想
  const hasEmptyItem = order.value.items.some(x => x.quantity === 0)
  if (hasEmptyItem) {
    showConfirmDialog({ message: '存在数量为0的项目, 订单未编辑完成。请修改后再打印' })
    return
  }

  showConfirmDialog({
    message: '是否打印销售单（显示价格）',
    confirmButtonText: '销售单',
    cancelButtonText: '出库单',
    closeOnClickOverlay: true,
  })
    .then(() => {
      printOrder(true)
    })
    .catch(() => {
      printOrder(false)
    })
}

function printOrder(showPrice = true) {
  printing.value = true
  OrderApi.print(id, showPrice)
    .then((ok) => {
      printing.value = false
      if (ok) {
        showSuccessToast('请求发送成功')
      }
      else {
        showSuccessToast('打印失败')
      }
    })
}

function onEdit() {
  router.push(`/orders/edit?id=${id}`)
}

async function invalidate() {
  if (order.value) {
    const ok = await OrderApi.invalidate(order.value.id)
    if (ok) {
      showSuccessToast('操作成功，订单已作废')
      order.value.invalid = true
    }
    else {
      showFailToast('操作失败，请联系管理员')
    }
  }
}

async function settle() {
  if (order.value) {
    const ok = await OrderApi.settle(order.value.id)
    if (ok) {
      showSuccessToast('操作成功，订单已结算')
      order.value.settled = true
    }
    else {
      showFailToast('操作失败，请联系管理员')
    }
  }
}

function onStub() {
  if (order.value) {
    router.push(`/orders/stub?id=${order.value.id}`)
  }
}

function goConsumer() {
  router.push(`/contacts/detail?id=${order.value?.consumer?.id}`)
}

const imgSrc = ref(null as any)
async function toImage() {
  const canvas = await html2canvas(imgSrc.value)
  const src = canvas.toDataURL()
  return src
}

function onShare() {
  showConfirmDialog({
    message: '是否展示金额',
    confirmButtonText: '展示(给客户)',
    cancelButtonText: '隐藏(给仓库)',
    closeOnClickOverlay: true,
  })
    .then(() => {
      modeShow()
      setTimeout(() => {
        toImage().then((src: string) => {
          imgDst.value.src = src
          imgDstShown.value = true
          modeBase()
        })
      }, 50)
    })
    .catch(() => {
      modeHide()
      setTimeout(() => {
        toImage()
          .then((src: string) => {
            imgDst.value.src = src
            imgDstShown.value = true
            modeBase()
          })
      }, 50)
    })
}

const gridColor = ref('#6b7280')
const amountHide = ref(false)
function modeBase() {
  gridColor.value = '#6b7280'
  amountHide.value = false
}

function modeShow() {
  gridColor.value = 'royalblue'
  amountHide.value = false
}

function modeHide() {
  gridColor.value = 'yellowgreen'
  amountHide.value = true
}

function onCopyOrder() {
  router.push(`/orders/edit?copy=${order.value?.id}`)
}

// setInterval(() => {
//   console.log(order.value);

// }, 2000)
</script>

<template>
  <div v-if="order && order.consumer" pb14>
    <Popup v-model:show="printing" b-rd-4 p4 :close-on-click-overlay="false">
      <Loading vertical>
        打印请求中
      </Loading>
    </Popup>
    <div ref="imgSrc" bg-light5>
      <PairsView
        mt2 :pairs="[
          ['客户', order.consumer.name, () => goConsumer()],
          ['批次', `第 ${order.batch} 单`],
          ['时间', Common.timeFormat(order.date)],
        ]"
      />

      <ItemsView ref="imgSrc" :color="gridColor" :amount-hide="amountHide" :order="order" />

      <DeliveryView :order="order" />

      <PairsView
        :pairs="[
          ['备注', order.notes],
        ]"
      />
    </div>

    <!-- 作废订单 -->
    <div v-if="order.invalid" mb paper bg-rose-1 b="1 solid rose">
      订单已经作废，不能进行任何操作。需要恢复请联系管理员
    </div>

    <!-- 结算订单 -->
    <div v-else-if="order.settled">
      <div paper bg-emerald-1 b="1 solid emerald">
        订单已经结算，不能进行编辑。需要修改请联系管理员
      </div>

      <ActionBar>
        <ActionBarIcon text="打印" @click="onPrint">
          <template #icon>
            <FontAwesomeIcon icon="print" color="rgb(59, 130, 246)" />
          </template>
        </ActionBarIcon>

        <ActionBarButton color="rgb(6, 182, 212)" text="存根" @click="onStub" />
        <ActionBarButton color="rgb(34, 197, 94)" text="分享" @click="onShare" />
      </ActionBar>
    </div>

    <!-- 默认菜单 -->
    <div v-else>
      <ActionBar>
        <ActionBarIcon text="作废" @click="protectedAction(invalidate, '确定要作废订单吗？')">
          <template #icon>
            <FontAwesomeIcon icon="trash-can" color="red" />
          </template>
        </ActionBarIcon>
        <ActionBarIcon text="打印" @click="onPrint">
          <template #icon>
            <FontAwesomeIcon icon="print" color="rgb(59, 130, 246)" />
          </template>
        </ActionBarIcon>
        <ActionBarIcon text="存根" @click="onStub">
          <template #icon>
            <FontAwesomeIcon icon="camera-retro" color="rgb(6, 182, 212)" />
          </template>
        </ActionBarIcon>
        <ActionBarIcon text="分享" @click="onShare">
          <template #icon>
            <FontAwesomeIcon icon="share-nodes" color="rgb(34, 197, 94)" />
          </template>
        </ActionBarIcon>
        <ActionBarIcon text="再来一单" @click="onCopyOrder">
          <template #icon>
            <FontAwesomeIcon icon="copy" color="rgb(59, 130, 246)" />
          </template>
        </ActionBarIcon>

        <ActionBarButton
          color="rgb(236, 72, 153)" text="结算"
          @click="protectedAction(settle, `确认该订单确认已经付款了吗？金额：${Common.totalAmount(order)}`)"
        />
        <ActionBarButton color="darkorange" text="编辑" @click="onEdit" />
      </ActionBar>
    </div>

    <div
      v-show="imgDstShown" fixed left-0 top-0 z-1000 h-screen w-screen flex flex-col items-center justify-center
      :style="{ background: '#000b' }" @click="imgDstShown = false"
    >
      <div mb-2 paper of-hidden p0>
        <img ref="imgDst" block w-80vw>
      </div>

      <div flex items-center c-white>
        <div>长按图片</div>
        <FontAwesomeIcon mx2 icon="arrow-right" />
        <div>分享</div>
      </div>
      <div flex items-center c-white>
        点击关闭
      </div>
    </div>
  </div>
</template>

<route lang="yaml">
meta:
  title: 订单详情
  keepAlive: true
</route>
